﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading.Tasks;

namespace KochamPycze.Analisys
{
    class SoundAnaliser
    {
        private SoundCapture Source;
        private readonly int BytesPerSample;
        private readonly int SampleRate;
        
        public SoundAnaliser(SoundCapture Source)
        {
            this.Source = Source;
            this.Source.DataAvailable += Analize;
            BytesPerSample = Source.WaveFormat.BitsPerSample / 8;
            SampleRate = Source.WaveFormat.SampleRate;
            if (Source.WaveFormat.Encoding.ToString() != "Pcm")
                throw new Exception("data format distinct from pcm");
        }

        public event Action<Note> NoteRecognized;

        //16 bitów 44.1khz
        private void Analize(int raw_len, byte[] raw_data)
        {
            int len, fq_len;
            double[] data, fq_data;
            ComputeData(raw_len,raw_data,out len, out data);
            ComputeFFT(len, data, out fq_len, out fq_data);
            //Analize data
            //print note
        }

        private void ComputeFFT(int len, double[]data, out int fq_len, out double[] fq_data){

            fq_len = 0;
            fq_data = null;
        }

        private void ComputeData(int raw_len, byte[] raw_data, out int len, out double[] data)
        {
            len = raw_len / BytesPerSample;     //adjust to real amount of data
            int i;
            for (i = 1; i < len; i *= 2) ;      //adjust to be power of two
            len = i;
            len /= 2;
     
            data = new double[len];
            int _byte;
            int value;
            double denom = 1 << (8*BytesPerSample);
            //trzeba sprawdzic który bajt jest bardziej znaczący !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            for (i = 0; i < len; ++i)
            {
                value = 0;
                for (int j = 0, k = BytesPerSample * i; j < BytesPerSample; ++j)
                {
                    _byte = raw_data[k+j];
                    value = (value << 8) | _byte;
                }
                data[i] = value / denom;
            }
        }
    }
}
